UVA-10305 Ordering Tasks(拓扑序 水题)

描述

传送门:UVA-10305 Ordering Tasks

John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is
only possible if other tasks have already been executed.

输入描述

The input will consist of several instances of the problem. Each instance begins with a line containing
two integers, 1 ≤ n ≤ 100 and m. n is the number of tasks (numbered from 1 to n) and m is the
number of direct precedence relations between tasks. After this, there will be m lines with two integers
i and j, representing the fact that task i must be executed before task j.
An instance with n = m = 0 will finish the input.

输出描述

For each instance, print a line with n integers representing the tasks in a possible order of execution.

示例

输入

1
2
3
4
5
6
5 4
1 2
2 3
1 3
1 5
0 0

输出

1
1 4 2 5 3

题解

题目大意

给出n组数据,前面的的序号表示这个任务先于后面序号的任务,要求将任务先后排序(不一定有一种)

思路

拓扑序模板题,将入度为零的点进队,每次出队更新入度,继续将入度为零的点进队,最后输出。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>
const int MAXN = 105, INF = 0x3f3f3f3f;
using namespace std;
int n, m, u, v;
int vis[MAXN], used[MAXN];
vector<int> E[MAXN];

int main(){
while(~scanf("%d %d", &n, &m) && (n || m)){
memset(vis, 0, sizeof(vis));
memset(used, 0, sizeof(used));
for(int i = 0; i <= n; i++) E[i].clear();
for(int i = 0; i < m; i++){
scanf("%d %d", &u, &v);
E[u].push_back(v);
vis[v]++;
}
queue<int>que, ans;
for(int i = 1; i <= n; i++){
if(vis[i] == 0){
que.push(i);
}
}
while(!que.empty()){
int now = que.front();
que.pop();
ans.push(now);
for(int i = 0; i < E[now].size(); i++){
if(--vis[E[now][i]] == 0){
que.push(E[now][i]);
}
}
}
printf("%d", ans.front());
ans.pop();
while(!ans.empty()){
printf(" %d", ans.front());
ans.pop();
}
printf("\n");
}
}

/*

5 4
1 2
2 3
1 3
1 5
0 0

*/